package org.groupg.practice;

import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.Collectors;

public class TaskGraph {

    // 任务结果类
        record TaskResult(int result) {
    }

    // 节点任务类
    private static class NodeTask extends RecursiveTask<TaskResult> {
        private final Graph<String, DefaultEdge> graph;
        private final String node;
        private final Map<String, TaskResult> resultsMap;

        public NodeTask(Graph<String, DefaultEdge> graph, String node, Map<String, TaskResult> resultsMap) {
            this.graph = graph;
            this.node = node;
            this.resultsMap = resultsMap;
        }

        @Override
        protected TaskResult compute() {
            List<String> predecessors = graph.incomingEdgesOf(node)
                    .stream()
                    .map(graph::getEdgeSource)
                    .toList();

            if (predecessors.isEmpty()) {
                // 没有前驱节点，直接计算结果
                int value = Integer.parseInt(node); // 假设节点名称是一个整数
                TaskResult result = new TaskResult(value);
                resultsMap.put(node, result);
                return result;
            }

            // 等待所有前驱节点完成
            List<NodeTask> tasks = predecessors.stream()
                    .map(predecessor -> new NodeTask(graph, predecessor, resultsMap))
                    .toList();

            for (NodeTask task : tasks) {
                task.invoke();
            }

            // 使用前驱节点的结果计算当前节点的结果
            int sum = tasks.stream()
                    .mapToInt(task -> resultsMap.get(task.node).result())
                    .sum();

            TaskResult result = new TaskResult(sum);
            resultsMap.put(node, result);
            return result;
        }
    }

    public static void main(String[] args) {
        Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class);

        // 添加节点和边
        graph.addVertex("1");
        graph.addVertex("2");
        graph.addVertex("3");
        graph.addVertex("4");

        graph.addEdge("1", "2");
        graph.addEdge("2", "3");
        graph.addEdge("1", "3");
        graph.addEdge("3", "4");

        String targetNode = "4";

        Map<String, TaskResult> resultsMap = new HashMap<>();
        ForkJoinPool forkJoinPool = new ForkJoinPool(1);
        NodeTask task = new NodeTask(graph, targetNode, resultsMap);

        TaskResult finalResult = forkJoinPool.invoke(task);
        System.out.println("Final result for node " + targetNode + ": " + finalResult.result());
    }
}